import { Component, OnInit } from '@angular/core';
import {
  FormGroup,
  FormControl,
  Validators,
  FormBuilder,
} from '@angular/forms';
import { Quote } from 'src/app/domain/quote.model';
import { QuoteService } from 'src/app/services/quote.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {
  form: FormGroup;
  quote: Quote = {
    cn: '不要只因一次挫败，就放弃你原来决心想达到的梦想。（莎士比亚）',
    en:
      'Do not, for one repulse, forgo the purpose that you resolved to effect.',
    pic: '/assets/img/quotes/2.jpg',
  };

  constructor(private fb: FormBuilder, private quoteService: QuoteService) {
    this.quoteService.getQuote().subscribe((q) => (this.quote = q));
  }

  ngOnInit(): void {
    // this.form = new FormGroup({
    //   email: new FormControl(
    //     'lionel_lc@163.com',
    //     Validators.compose([Validators.required, Validators.email])
    //   ),
    //   password: new FormControl('', Validators.required),
    // });

    this.form = this.fb.group({
      email: [
        'lionel_lc@163.com',
        Validators.compose([
          Validators.required,
          Validators.email,
          this.validate,
        ]),
      ],
      password: ['', Validators.required],
    });
  }

  onSubmit({ value, valid }, ev: Event): void {
    ev.preventDefault();

    // this.form.controls['email'].setValidators(this.validate);
    console.log(value, valid);
  }

  validate(c: FormControl): { [key: string]: any } {
    if (!c.value) {
      return null;
    }

    const pattern = /^lionel+/;
    if (pattern.test(c.value)) {
      return null;
    }

    return {
      emailNotVailed: 'email is no validate',
    };
  }
}
